<template>
  <div class="app-declare-container">
    <nu-col :span="24" style="width:100%;height:100%">
      <nu-row class="row" :gutter="20" ref="formData">
        <nu-col :span="24" class="col">
          <span class="hint">可手动维护日发电计划考核、调峰考核下的免考核场景。

            系统自动识别的免考核场景包括：机组被指定以自动调节模式（除严格跟踪基点子模式外）提供AGC 辅助服务期间、系统超出爬坡能力免考核、电网频率高于50.1Hz 而机组有功出力越下限、当电网频率低于49.9Hz
            而机组有功出力越上限、机组启停过程免考核。</span>

        </nu-col>
        <nu-col :span="24" class="col">
          <nu-button type="primary" class="searchButton" @click="addTable">新增</nu-button>
        </nu-col>
        <nu-col :span="24">
          <div class="line"></div>
        </nu-col>
      </nu-row>
      <NuTableList :showFilter="false" :columns="columns" :dataSource="dataSource" :options="options"
        :operates="operates(this)" :pagination="pagination" @handleSizeChange="handleSizeChange"
        @handleChangePage="handleChangePage" @handleCurrentChange="handleCurrentChange" style="margin: 0 0 20px 0">
      </NuTableList>
    </nu-col>
    <!-- </nu-row> -->
    <nu-dialog :title="dialogTitle" :visible.sync="dialogShow" width="800px" :close-on-click-modal="false" top="5vh"
      :modal-append-to-body="false" @close="diaClose">
      <div class="dialogHeaderSearch">
        <NuVerifyForm :model="dialogFormData" ref="dialogFormData" label-width="130px" class="submitForm"
          @submitForm="diaSubmitForm" :buttons="fyButtons">
          <NuformItem label="免考核类型：" prop="uncheckType" width="50%" :rules="[{ required: true, message: ' 免考核类型不能为空' }]">
            <nu-select class="searchSelect" :filterable="true" :list="nameList" type="text" :valueName="'dictActualValue'"
              :label="'dictName'" v-model="dialogFormData.uncheckType" autocomplete="off"
              style="width: calc(100% - 5px); margin-left: 2px">
            </nu-select>
          </NuformItem>
          <NuformItem label="免考核机组：" prop="bidUnitId" width="50%" :rules="[{ required: true, message: ' 免考核机组不能为空' }]">
            <el-select v-model="dialogFormData.bidUnitId" multiple filterable allow-create default-first-option
              placeholder="请选择调峰机组">
              <el-option v-for="item in bidUnitIdList" :key="item.value" :label="item.phyunitName"
                :value="item.phyunitId">
              </el-option>
            </el-select>
          </NuformItem>
          <NuformItem label="免考核日期范围" prop="time" width="50%" :rules="[
            { required: true, message: '免考核日期范围不能为空' },
          ]">
            <el-date-picker v-model="dialogFormData.time" type="daterange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" style="width: 100%" value-format="yyyy-MM-dd">
            </el-date-picker>
          </NuformItem>
          <NuformItem label="免考核时段范围" prop="timePicker" width="50%" :rules="[
            { required: true, message: '免考核时段范围不能为空' },
          ]">
            <TimePicker v-model="dialogFormData.timePicker" :minutesStep="5">
            </TimePicker>
          </NuformItem>
          <div class="connentBox">
            例如：2023年11月1日-12月30日0:30-7:00免考核，请在免考核日期范围选择2023年11月1日-2023年12月30日，免考时段范围选择0:30-7:00
          </div>
          <NuformItem label="免考核原因" prop="uncheckReason" width="100%" :rules="[
            { required: true, message: '免考核原因不能为空' },
          ]">

            <el-input type="textarea" :rows="4" placeholder="请输入内容" v-model="dialogFormData.uncheckReason">
            </el-input>
          </NuformItem>
        </NuVerifyForm>
        <nu-button class="dialogSearchButton" type="primary" @click="diaClose">取消</nu-button>
        <nu-button class="dialogSearchButton" type="primary" @click="diaSave">确定</nu-button>
      </div>
    </nu-dialog>
  </div>
</template>
<script>
import nuCol from "@/components/base/col.vue";
import nutbTitle from "@/components/base/tableTitle.vue";
import NuVerifyForm from "@/components/verify-form";
import NuformItem from "@/components/verify-form/form-item.vue";
import nuInput from "@/components/base/input";
import nuSelect from "@/components/base/select";
import nuButton from "@/components/base/button";
import NuTableList from "@/components/tableList/TableFormList";
import nuRow from "@/components/base/row.vue";
import nuDialog from "@/components/base/dialog";
import TimePicker from "@/components/TimeTicker";
import { getDateTime, replaceDateTime } from "@/utils/ruoyi";
const operates = (that) => [
  {
    label: "修改",
    icon: "",
    width: "50px",
    isShow: (row) => {
      return true;
    },
    disabled: (row) => {
      return false;
    },
    method: (row) => {
      that.openEdit(row);
    },
  },
  {
    label: "删除",
    icon: "",
    width: "50px",
    isShow: (row) => {
      return true;
    },
    disabled: (row) => {
      return false;
    },
    method: (row) => {
      that.deleteRow(row);
    },
  },
];
export default {
  name: "declare",
  components: {
    nuCol,
    nutbTitle,
    NuVerifyForm,
    NuformItem,
    nuInput,
    nuSelect,
    nuButton,
    NuTableList,
    nuRow,
    nuDialog,
    TimePicker,
  },
  data() {
    return {
      operates,
      currentRow: null,
      dataSource: [],
      bidUnitIdList: [],
      columns: [
        {
          label: "序号",
          prop: "index",
          width: "70px",
          render: (h, params) => {
            // return h("span", params.index + 1);
            return h('span', params.index + 1 + (this.pagination.pageNum - 1) * this.pagination.pageSize);
          },
        },
        {
          label: "免考核类型",
          prop: "uncheckTypeName",
          width: 150,
        },
        {
          label: "免考核机组",
          prop: "bidUnitName",
          width: 200,
        },
        {
          label: "免考核日期范围",
          prop: "time",
          width: 200,
          render: (h, params) => {
            if (params.row.unCheckStartDate && params.row.unCheckEndDate) {
              return h("span", replaceDateTime(params.row.unCheckStartDate, 'day') + " - " + replaceDateTime(params.row.unCheckEndDate, 'day'));
            } else {
              return ''
            }

          },
        },
        {
          label: "免考时间范围",
          prop: "time",
          width: 150,
          render: (h, params) => {
            if (params.row.unCheckStartTime && params.row.unCheckEndTime) {
              return h("span", `${replaceDateTime(params.row.unCheckStartTime, 'time')} - ${replaceDateTime(params.row.unCheckEndTime, 'time')}`);
            } else {
              return ''
            }

          },
        },
        {
          label: "免考核原因",
          prop: "uncheckReason",
        },
        {
          label: "记录维护时间",
          prop: "updateDate",
          width: 200,
        },
      ],
      options: {
        "default-expand-all": true,
        "element-loading-background": "rgba(225,239,242)",
        "element-loading-text": "数据正在加载中",
        "row-key": "pid",
        "header-cell-style": {
          background: "rgba(105, 159, 209, 0.7)",
          color: "#fff",
          fontWeight: "bold",
          fontsize: "16px",
        },
        height: "calc(100vh - 370px)",
      },
      dialogTitle: "",
      dialogShow: false,
      dialogFormData: {
        bidUnitId: [],
        time: [],
        uncheckType: "",
        uncheckReason: "",
        updateDate: "",
        timePicker: [],
        unCheckStartDate: "",
        unCheckEndDate: "",
        unCheckStartTime: "",
        unCheckEndTime: ""
      },
      nameList: [{ label: "机组1", value: 1 }, { label: "机组2", value: 2 }],
      typeList: [
        { label: "日前申报", value: 1 },
        { label: "临时申报", value: 2 },
      ],
      fyButtons: [],
      pagination: {
        pageSize: 20,
        total: 0,
        pageNum: 1,
      },
    };
  },
  mounted() {
    this.getDeclareData();
    this.getUncheckType()
    this.getCrewManageTableData()
  },
  methods: {
    /**
     * 获取表格数据
     */
    getDeclareData() {
      this.$httpGet(window.api.unCheckList, this.pagination)
        .then((res) => {
          if (res.code == 200) {
            this.dataSource = res.rows;
            this.pagination.total = res.total
          } else {
            this.dataSource = [];
          }
        })
        .catch((err) => {
          this.dataSource = [];
        });
    },
    /**
     * 新增
     */
    addTable() {
      this.dialogTitle = "新增";
      this.dialogShow = true;
    },

    // 获取机组
    getCrewManageTableData() {
      let postData = {
        pageSize: 99999,
        total: 0,
        pageNum: 1,
        phyunitName: ""
      };
      for (let k in postData.query) {
        if (postData.query[k] && Object.prototype.toString.call(postData.query[k]) == '[object String]') {
          postData.query[k] = postData.query[k].toString().trim();
        }
      }
      this.$httpGet(window.api.getCrewManageTableData, postData).then(res => {
        if (res.code == 200 && res.rows) {
          this.bidUnitIdList = res.rows
        } else {
        }
      }).catch(err => {

      });
    },
    // 修改
    unCheckEdit() {
      let postData = {
        ...this.dialogFormData,
      };
      if (postData.bidUnitId instanceof Array) {
        postData.bidUnitId = postData.bidUnitId.join()
      }
      let time1 = getDateTime('obj', this.dialogFormData.timePicker[0])
      let time2 = getDateTime('obj', this.dialogFormData.timePicker[1])
      postData['unCheckStartDate'] = getDateTime('day', this.dialogFormData.time[0], false)
      postData['unCheckEndDate'] = getDateTime('day', this.dialogFormData.time[1], false)
      postData['unCheckStartTime'] = time1.curHours + time1.curMinutes + time1.curSeconds
      postData['unCheckEndTime'] = time2.curHours + time2.curMinutes + time2.curSeconds
      postData?.time ? delete postData.time : ''
      postData?.timePicker ? delete postData.timePicker : ''
      if (postData.relatedDevId == postData.relatedDevName) {
        postData.relatedDevId == postData.oldRelatedDevId;
      }
      for (let k in postData.query) {
        if (
          postData.query[k] &&
          Object.prototype.toString.call(postData.query[k]) == "[object String]"
        ) {
          postData.query[k] = postData.query[k].toString().trim();
        }
      }
      this.$httpPut(window.api.unCheckEdit, postData)
        .then((res) => {
          if (res.code == 200) {
            this.$message({
              message: res.msg,
              type: "success",
            });
            this.diaClose();
            this.getDeclareData();
          } else {
          }
        })
        .catch((err) => { });
    },
    /**
     * 免考核类型
     */
    getUncheckType() {
      this.$httpGet(window.api.getOneLevelDicts, {
        dictType: "UNCHECK_TYPE",
        pageSize: 9999,
        pageNum: 1,
      })
        .then((res) => {
          if (res.code == 200) {
            this.nameList = res.rows;
          } else {
          }
        })
        .catch((err) => { });
    },

    // 新增
    unCheckAdd() {
      let postData = {
        ...this.dialogFormData,
      };
      postData.bidUnitId = postData.bidUnitId.join()
      let time1 = getDateTime('obj', this.dialogFormData.timePicker[0])
      let time2 = getDateTime('obj', this.dialogFormData.timePicker[1])
      postData['unCheckStartDate'] = getDateTime('day', this.dialogFormData.time[0], false)
      postData['unCheckEndDate'] = getDateTime('day', this.dialogFormData.time[1], false)
      postData['unCheckStartTime'] = time1.curHours + time1.curMinutes + time1.curSeconds
      postData['unCheckEndTime'] = time2.curHours + time2.curMinutes + time2.curSeconds
      delete postData.time
      delete postData.timePicker
      for (let k in postData.query) {
        if (
          postData.query[k] &&
          Object.prototype.toString.call(postData.query[k]) == "[object String]"
        ) {
          postData.query[k] = postData.query[k].toString().trim();
        }
      }
      this.$httpPost(window.api.unCheckAdd, postData)
        .then((res) => {
          if (res.code == 200) {
            this.$message({
              message: "添加成功",
              type: "success",
            });
            this.diaClose();
            this.getDeclareData();
          } else {
            this.$message({
              message: "添加失败",
              type: "info",
            });
          }
        })
        .catch((err) => { });
    },
    /**
     * form组件内置查询事件
     */
    searchForm(val) {
      if (val) {
        this.getDeclareData();
      }
    },
    /**
     * 弹窗-保存
     */
    diaSave() {
      this.$refs["dialogFormData"].submitForm("form");
    },
    /**
     * 弹窗-关闭
     */
    diaClose() {
      this.dialogShow = false;
      this.resetForm("dialogFormData");
      this.dialogFormData.uncheckType = ''
    },
    /**
      * 重置表单
      */
    resetForm(formName) {
      this.$refs[formName].resetForm("form");
      for (let k in this[formName]) {
        if (
          Object.prototype.toString.call(this[formName][k]) == "[object String]"
        ) {
          this[formName][k] = "";
        } else if (
          Object.prototype.toString.call(this[formName][k]) == "[object Array]"
        ) {
          this[formName][k] = [];
        } else if (
          Object.prototype.toString.call(this[formName][k]) == "[object Number]"
        ) {
          this[formName][k] = 0;
        }
      }
    },
    inputFunc(val) {
      this.dialogFormData.time = val.value
    },
    /**
     * 每页条数变化事件
     */
    handleSizeChange(val) {
      this.pagination.pageNum = 1;
      this.pagination.pageSize = val;
      this.getDeclareData();
    },
    /**
     * 改变分页触发事件
     */
    handleChangePage(val) {
      this.pagination.pageNum = val;
      this.getDeclareData();
    },
    /**
     * 单选
     */
    handleCurrentChange(val) {
      this.currentRow = val;
    },
    /**
     * dialogFormData组件内置提交事件
     */
    diaSubmitForm(val) {
      if (val) {
        if (this.dialogTitle == "修改") {
          this.unCheckEdit()
        } else if (this.dialogTitle == "新增") {
          this.unCheckAdd()
        }
      }
    },
    /**
     * 表格-修改
     */
    openEdit(row) {
      this.dialogTitle = "修改";
      this.dialogShow = true;
      row.timePicker = [
        replaceDateTime(row.unCheckStartDate, 'day') + ' ' +
        replaceDateTime(row.unCheckStartTime, 'time'),
        replaceDateTime(row.unCheckEndDate, 'day') + ' ' +
        replaceDateTime(row.unCheckEndTime, 'time')]
      row.time = [replaceDateTime(row.unCheckStartDate, 'day'), replaceDateTime(row.unCheckEndDate, 'day')]

      if (row.bidUnitId instanceof Array) {

      } else {
        row.bidUnitId = row.bidUnitId.split(",")
      }
      Object.assign(this.dialogFormData, row);
    },



    // 删除一行
    deleteRow(row) {
      this.$confirm("确定要删除吗？", "确认删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.unCheckRemove(row);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    unCheckRemove(row) {
      this.$httpDel(window.api.unCheckRemove, row.id)
        .then((res) => {
          if (res.code == 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getDeclareData();
          } else {
          }
        })
        .catch((err) => { });
    },
  },
};
</script>
<style scoped>
.app-declare-container {
  height: calc(100vh - 70px);
}

.hint {
  display: block;
  font-size: 14px;
  line-height: 28px;
  color: rgba(79, 84, 112, 1);
}

.dialogHeaderSearch {
  background-color: var(--model-bgc);
  padding: 10px;
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  justify-content: right;
}

.el-col {
  margin: 0;
}

.row {
  margin-left: 0 !important;
  margin-right: 0 !important;
}

.col {
  padding: 0px 10px 0px 10px;
}

.connentBox {
  margin-top: 20px;
  margin-left: 20px;
  color: brown;
}

.submitForm {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.el-form-item {
  margin: 0;
  margin-bottom: 16px !important;
}

::v-deep .el-form-item__error {
  padding-top: 2px !important;
}

::v-deep .zm-time-picker {
  border-radius: 4px;
  height: 36px;
}

.el-textarea {
  margin-bottom: 6px;
}
</style>
